package com.example.photographWatermark

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.util.Log
import androidx.annotation.NonNull
import androidx.annotation.Nullable
import com.example.photographWatermark.camera2.CameraActivity
import com.example.photographWatermark.helper.ActivityHelper
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import io.flutter.plugin.common.PluginRegistry
import io.flutter.plugin.common.PluginRegistry.ActivityResultListener
import io.flutter.plugin.common.PluginRegistry.Registrar

/** PhotographWatermarkPlugin */
public class PhotographWatermarkPlugin :
        FlutterPlugin, MethodCallHandler, ActivityAware, ActivityResultListener {
    /// The MethodChannel that will the communication between Flutter and native Android
    ///
    /// This local reference serves to register the plugin with the Flutter Engine and unregister it
    /// when the Flutter Engine is detached from the Activity
//    private lateinit var channel: MethodChannel

    private lateinit var mActivity: Activity
    private lateinit var mContext: Context
    private lateinit var mResult: Result





    @Nullable
    private var channelHandler: ChannelHandler? = null

    @Nullable
    private var activityHelper: ActivityHelper? = null

    override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        Log.d("---onAttachedToEngine", "---")
//        channel = MethodChannel(flutterPluginBinding.getFlutterEngine().getDartExecutor(), "ktx.com.photographWatermark")
//        channel.setMethodCallHandler(this);
        mContext = flutterPluginBinding.applicationContext
        activityHelper = ActivityHelper(flutterPluginBinding.applicationContext)

        channelHandler = ChannelHandler(activityHelper!!)
        val methodChannel = MethodChannel(flutterPluginBinding.binaryMessenger, "ktx.com.photographWatermark")
        methodChannel.setMethodCallHandler(this)
//        methodChannel.setMethodCallHandler(channelHandler)
//        channelHandler!!.startListening(methodChannel)
    }


    // This static function is optional and equivalent to onAttachedToEngine. It supports the old
    // pre-Flutter-1.12 Android projects. You are encouraged to continue supporting
    // plugin registration via this function while apps migrate to use the new Android APIs
    // post-flutter-1.12 via https://flutter.dev/go/android-project-migration.
    //
    // It is encouraged to share logic between onAttachedToEngine and registerWith to keep
    // them functionally equivalent. Only one of onAttachedToEngine or registerWith will be called
    // depending on the user's project. onAttachedToEngine or registerWith must both be defined
    // in the same class.
    companion object {
         var name:String? = null
        var address:String? = null
        var time:String? = null

        @JvmStatic
        fun registerWith(registrar: Registrar) {
//            val instance = PhotographWatermarkPlugin()
            val methodChannel = MethodChannel(registrar.messenger(), "ktx.com.photographWatermark")
//            methodChannel.setMethodCallHandler(this)
            methodChannel.setMethodCallHandler(PhotographWatermarkPlugin())
            val channelHandler = ChannelHandler(ActivityHelper(
                    registrar.context(),
                    registrar.activity()
            ))
//            methodChannel.setMethodCallHandler(channelHandler)
//            methodChannel.setMethodCallHandler(this)
//            handler.startListening(channel)

        }
    }

//    override fun onAttachedToActivity(binding: ActivityPluginBinding) {
////        mActivity = ActivityPluginBinding.activity
//    }

    override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
//        Log.d("---onMethodCall","---$mRegistrar")
        mResult = result
        name = call.argument("name")
        address= call.argument("address")
        time= call.argument("time")
        when (call.method) {
            "takePhoto" -> {
//                val intent = Intent()
//                intent.action = "camera"
//                mActivity.startActivityForResult(intent,1)
                val intent = Intent(mContext, CameraActivity::class.java)
                intent.putExtra("name",name)
                intent.putExtra("address",address)
                intent.putExtra("time",time)
                mActivity.startActivityForResult(intent, 1)
            }
            "getPlatformVersion" -> {
                result.success("Android ${android.os.Build.VERSION.RELEASE}")
            }
            else -> {
                result.notImplemented()
            }
        }
    }


    override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
//        channel.setMethodCallHandler(null)
        if (channelHandler == null) {
            return
        }

        channelHandler!!.stopListening()
        channelHandler = null
        activityHelper = null
    }


    override fun onDetachedFromActivity() {

    }

    override fun onDetachedFromActivityForConfigChanges() {
        onDetachedFromActivity()
    }

    override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
        onAttachedToActivity(binding)
    }

    override fun onAttachedToActivity(binding: ActivityPluginBinding) {
//        activityBinding = binding
        mActivity = binding.activity
        if (channelHandler == null) {
            return
        }
        binding.addActivityResultListener(this)
//        binding.addRequestPermissionsResultListener(activityHelper!!)
//        activityHelper!!.activity = binding.activity

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?): Boolean {
        Log.d("============================", "============================")
        val path = data?.getStringExtra("imagePath")
//        val path1 = data?.getStringExtra("camera")
        Log.d("-----onActivityResult", "---$path")
        Log.d("-----onActivityResult", "---${MainActivity.imagePath}")
        Log.d("-----requestCode", "---$requestCode")

        when (requestCode) {
            1 ->  if(MainActivity.imagePath!=null) {
                mResult.success(MainActivity.imagePath)
            }
            else -> return false
        }
        return true
    }
}
